package com.jackstraw.jack_base.rules.entity.bo;

import com.jackstraw.jack_base.rules.entity.po.ImportPackagePo;
import com.jackstraw.jack_base.rules.entity.po.RuleGroupPo;
import com.jackstraw.jack_base.util.CollectionUtil;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

import java.math.BigDecimal;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * 规则组表  BO
 *
 * @author zhaozhao 945514650@qq.com
 * @since version:1.0 generatorDate:2022-12-04 14:28:29
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class RuleGroupBo extends RuleGroupPo {

    /**
     * 排序
     */
    private BigDecimal sort;

    /**
     * 导入的包
     */
    private final Set<String> importPackages = new HashSet<>(0);

    /**
     * 规则组关联的规则
     */
    private List<RuleBo> ruleBos;

    /**
     * 规则组对应的规则ID
     */
    private List<Long> ruleIdS;


    public Set<String> getImportPackages() {
        if (CollectionUtil.isNotEmpty(this.getRuleBos())) {
            this.getRuleBos().stream()
                    .filter(ruleBo
                            -> CollectionUtil.isNotEmpty(ruleBo.getImportPackages()))
                    .forEach(ruleBo
                            -> this.importPackages.addAll(
                            ruleBo.getImportPackages()
                                    .stream()
                                    .map(ImportPackagePo::getPackageName)
                                    .collect(Collectors.toSet())));
        }
        return importPackages;
    }

    /**
     * 拼接得到规则文件
     *
     * @return
     */
    public String getRuleDrl() {
        StringBuffer stringBuffer = new StringBuffer();

        stringBuffer.append("package ")
                .append(this.getPackageName())
                .append("\n");

        if (CollectionUtil.isNotEmpty(this.getImportPackages())) {
            this.getImportPackages().forEach(importPackageName
                    -> stringBuffer
                    .append("import ")
                    .append(importPackageName)
                    .append("\n"));
        }

        if (CollectionUtil.isNotEmpty(this.getRuleBos())) {
            this.getRuleBos().forEach(ruleBo
                    -> stringBuffer
                    .append(ruleBo.getRuleText())
                    .append("\n"));
        }

        return stringBuffer.toString();
    }

}